<?php include("/includes/header.php") ?>
<?php include("/includes/sidebar.php") ?>
<?php 
	$idmeja_en = $_GET[trim(base64_encode("id"), '=')]; 
	$idmeja = base64_decode($idmeja_en);
	$date = date("Y-m-d");


	$sql_resto = "SELECT * FROM resto WHERE no_meja = '$idmeja' ORDER BY id DESC LIMIT 1";
	$query_resto = mysql_query($sql_resto);
	if (mysql_num_rows($query_resto) > 0) {
		$query_resto = mysql_query($sql_resto);
		$result_resto = mysql_fetch_array($query_resto);

		$sql_nota = "SELECT * FROM nota WHERE idresto = '$result_resto[id]' AND is_paid = 1";
		$query_nota = mysql_query($sql_nota);
		$jumlah_nota = mysql_num_rows($query_nota);
		if ($jumlah_nota > 0) {
			$sql_resto_menu = "SELECT * FROM resto_menu WHERE idresto = '$result_resto[id]' GROUP BY bill";
			$query_resto_menu = mysql_query($sql_resto_menu);
			$jumlah_resto_menu = mysql_num_rows($query_resto_menu);
			if ($jumlah_nota == $jumlah_resto_menu) {
				$class_book = "";
			} else {
				$class_book = "booked";	
			}
		} else {
			$class_book = "booked";
		}
	} else {
		$class_book = "";
	}



	// $sql_resto = "SELECT * FROM resto WHERE no_meja = '$idmeja' AND id NOT IN (SELECT idresto FROM nota WHERE is_paid = 0)";
	// $query_resto = mysql_query($sql_resto);
	// if (mysql_num_rows($query_resto) == 0) {
	if ($class_book != "booked") {
		$act_form = "new";
		$idresto = 0;
		$disabled = "";
		$btn_disabled = "disabled";
	} else {
		$query_resto = mysql_query($sql_resto);
		$resto = mysql_fetch_array($query_resto);
		$act_form = "edit";
		$idresto = $resto[id];
		$disabled = "disabled";
		$btn_disabled = "";
	}
?>

<style type="text/css">
	.input-table-placer {
		padding: 0 !important;
		vertical-align: middle !important;
		border-bottom: 2px solid #8DC2F7 !important;
	}
	.input-table {
		margin: 0 !important;
		box-shadow: none !important;
		border-radius: 0 !important;
		border: none !important;
		background-color: transparent !important;
		width: 40px !important;
	}
	.input-menu {
		width: 100% !important;
	}
	.input-jumlah {
		width: 100%;
	}
	.table-add-order {
		border-top: 1px solid #CCC;
		margin-top: 20px;
	}
</style>

<div class="header">
	<span>
		<a href="resto.php">
			<i class="fa fa-cutlery"></i> Restaurant
		</a>
	</span>
	<span>
		<a href="resto-invoice-list.php">
			<i class="fa fa-list-alt"></i> Invoice List
		</a>
	</span>
</div>

<div class="breadcumb">
	<ul>
		<li>
			<a href="resto.php">Table List</a>
			<span class="divider"><i class="fa fa-angle-right"></i></span>
		</li>
		<li>
			<a href="resto-trans.php?<?php echo trim(base64_encode("id"), '=')."=".base64_encode($idmeja) ?>">Order Form</a>
		</li>
	</ul>
	<div class="clear"></div>
</div>

<form class="form-horizontal" data-id="<?php echo $idmeja ?>">
	<div class="content row-fluid"> 
		<div class="span6">

			<input type="hidden" class="no_meja" value="<?php echo $idmeja; ?>">
			<input type="hidden" class="act_form" value="<?php echo $act_form; ?>">
			<input type="hidden" class="idresto" value="<?php echo $idresto; ?>">
			<div class="alert_container"></div>


    	<div>
  			<div class="alert alert-info"> Add Order </div>
    		<div>
    			<div class="row-fluid">
  					<div class="span6">
    					<label class="left">Table
    					<input type="text" class="disabled left" style=" margin-left: 10px; width: 30px; text-align: center;" value="<?php echo $idmeja ?>" disabled>
  					</div>
  					<div class="span6">
    					<label class="right">Date
    						<input style=" margin-left: 10px; display: inline;" placeholder="Masukkan Tanggal" type="date" data-date="" data-date-format="yyyy-mm-dd" data-date-autoclose="true" data-date-start-view="day" data-date-minviewmode="date" class="datePicker tanggal right" value="<?php echo $date; ?>" <?php echo $disabled ?>>
    					</label>
  					</div>
    			</div>
					<div style="margin-top: 20px;">
						<div class="span12">
							<ul class="breadcrumb" style="margin-bottom: 0; border-top: 1px dashed #DDD; background-color: transparent;">
								<button type="submit" class="btn btn-info btn-simpan f2">
									<i class="fa fa-check"></i>
									Save (F2)
								</button>
								<button class="btn add-line f3">
									<i class="fa fa-plus"></i>
									Add row (F3)
								</button>
								<button class="btn btn-danger remove-last-line f4">
									<i class="fa fa-trash-o"></i>
									Delete last line (F4)
								</button>
							</ul>
						</div>
					</div>
					<div class="clear"></div>
    			<div class="f1 input-table-focus btn-success" style="padding: 5px; font-weight: bold;">Input List Order (F1)</div>
					<table class="table table-striped table-add-order" style="margin-top: 0;">
						<thead>
							<tr class="alert-info">
								<th style="width: 10px;">No</th>
								<th>
									Menu
									<a href="#">
								  	<span style="background-color: #EEE; border: 1px solid #CCC; padding: 5px 8px; margin-left: 5px;"><i class="fa fa-plus plus-menu"></i></span>
	    						</a>
	    					</th>
								<th style="width: 3px;"></th>
								<th style="width: 30px;">Quantity</th>
								<th style="width: 10px;"></th>
							</tr>
						</thead>
						<tbody id="order-placer">
							<?php for ($i=1; $i <= 8 ; $i++) { ?>
								<tr>
									<td class="no">
										<?php echo $i; ?>
									</td>
									<td class="input-table-placer input-menu-placer">
										<input type="text" class="input-table input-menu">
										<input type="hidden" class="idmenu">
									</td>
									<td></td>
									<td class="input-table-placer input-jumlah-placer">
										<input type="number" class="input-table input-jumlah">
									</td>
									<td><a href="#" class="remove-line"><i class="fa fa-times"></i></a></td>
								</tr>
							<?php } ?>
						</tbody>
					</table>	
    		</div>
    	</div>
		</div>

		<div class="span6">
			<div class="alert alert-info" style="margin-bottom: 0;">
				Order List
	    </div>

	    <ul class="breadcrumb well btn-action" style="background-color: transparent; border-bottom: 1px dashed #DDD; margin-bottom: 0;">
				<a href="resto-nota.php?<?php echo trim(base64_encode("id"), '=')."=".base64_encode($idresto) ?>" class="btn btn-success btn-nota f6" <?php echo $btn_disabled ?>>
					<i class="fa fa-list-alt"></i>
					Invoice (F6)
				</a>
				<button class="btn btn-edit-list f7" <?php echo $btn_disabled ?>>
					<i class="fa fa-pencil"></i>
					Edit List (F7)
				</button>
				<button class="btn btn-reset-list f8" <?php echo $btn_disabled ?>>
					<i class="fa fa-refresh"></i>
					Reset List (F8)
				</button>
				<button class="btn btn-danger btn-delete-list f9" <?php echo $btn_disabled ?>>
					<i class="fa fa-trash-o"></i>
					Delete Order (F9)
				</button>
			</ul>

	    <div id="order_list">
	    	<table class="table table-striped">
					<thead>
						<tr>
							<th style="width: 20px;">No</th>
							<th>Menu</th>
							<th>Quantity</th>
							<th>Price</th>
							<th>Total</th>
						</tr>
					</thead>
					<tbody id="order-list-placer">

					<?php
						$i = 1;
						$sql_resto_menu = "SELECT *, SUM(jumlah) AS jumlah_sum FROM resto_menu WHERE idresto = '$idresto' GROUP BY idmenu";
						$query_resto_menu = mysql_query($sql_resto_menu);
						if (mysql_num_rows($query_resto_menu) > 0) {
							$query_resto_menu = mysql_query($sql_resto_menu);
							while ($result_resto_menu = mysql_fetch_array($query_resto_menu)) {
								$sql_menu = "SELECT * FROM menu WHERE id = '$result_resto_menu[idmenu]'";
								$query_menu = mysql_query($sql_menu);
								$result_menu = mysql_fetch_array($query_menu);
					?>
						<tr>
							<td><?php echo $i; ?></td>
							<td><?php echo $result_menu[nama]; ?></td>
							<td><?php echo $result_resto_menu[jumlah_sum] ?></td>
							<td><?php echo $result_menu[harga] ?></td>
							<td><?php echo $result_resto_menu[jumlah_sum] * $result_menu[harga] ?></td>
						</tr>
					<?php
								$i++;
							}
						} else {
					?>
						<tr>
							<td colspan="5">Nothing has been ordered yet</td>
						</tr>
					<?php
						}
					?>
					</tbody>
				</table>
	    </div>
		</div>
	</div>
</form>

<div class="footer">
</div>

<?php include("/includes/footer.php") ?>   

<script type="text/javascript">
	function set_no() {
		i = 1;
		$('.table-add-order').find('tbody').find('tr').each(function(index, el) {
			$(this).find('.no').html(i);
			i = i + 1;
		});
	}

	function move_up(array_html, i){
    if($(array_html[i-1]).attr('disabled') == 'disabled'){
       move_up(array_html, i-1);
       return;
    }
    $(array_html[i-1]).focus();
  }

	function move_down(array_html, i){
	  if($(array_html[i+1]).attr('disabled') == 'disabled'){
	     move_down(array_html, i+1);
	     return false;
	  }
	  $(array_html[i+1]).focus();
	  return false;
	}

	function moveable_in_table(){
    var input_menus = $(".input-menu");
    var input_jumlahs = $(".input-jumlah");

    if(input_menus.length > 0){
      $.each(input_menus, function(i, l){
        $(l).on("keydown", function (e) {
          if (e.keyCode == 37) { //kiri
          }
          if (e.keyCode == 38) { //atas
          	if ($(l).val() == "") {
	          	e.preventDefault();
	            move_up(input_menus, i);
          	};
          }
          if (e.keyCode == 39) { //kanan
            e.preventDefault();
            $(input_jumlahs[i]).focus();
          }
          if (e.keyCode == 40) { //bawah
          	if ($(l).val() == "") {
	          	e.preventDefault();
	            move_down(input_menus, i);
          	};
          }
        });
      });
    }

    if(input_jumlahs.length > 0){
      $.each(input_jumlahs, function(i, l){
        $(l).on("keydown", function (e) {
          if (e.keyCode == 37) { //kiri
            // if($(l).caret().start == 0){
          		// alert("haha");
            // }
            e.preventDefault();
            $(input_menus[i]).focus();
          }
          if (e.keyCode == 38) { //atas
            e.preventDefault();
            move_up(input_jumlahs, i);
          }
          if (e.keyCode == 39) { //kanan
          }
          if (e.keyCode == 40) { //bawah
            e.preventDefault();
            move_down(input_jumlahs, i);
          }
        });
      });
    }
  }

	$(document).ready(function() {
		moveable_in_table();
		$('.input-table-focus').click(function(event) {
			$('.table-add-order').find('tbody').find('tr:first-child').find('.input-menu').focus();
		});

		if ($('.act_form').val() == "new") {
			$('.idagent').focus();
		};

		$('.btn-simpan').click(function(event) {
			event.preventDefault();

			var menu_list = [];
			var table_sum = 0;
			$('.table-add-order').find('tbody').find('tr').each(function(index, el) {
				if ($(this).find('.idmenu').val() != "" && $(this).find('.input-jumlah').val() != "") {
					table_sum = table_sum + 1;
					var each_menu = [];
					each_menu.push($(this).find('.idmenu').val());
					each_menu.push($(this).find('.input-jumlah').val());
					menu_list.push(each_menu);
				};
			});

			if (table_sum > 0) {
				var formResto = {
					order_menu: menu_list,
					no_meja: $('form').data("id"),
					tanggal: $('.tanggal').val(),
					idresto: $('.idresto').val(),
					act_form: $('.act_form').val(),
					act: 2
				}

				$.ajax({
					url: '/action/act_resto.php',
					type: 'POST',
					data: formResto,
					cache: false, 
	        success: function(data){
	        	if (data == "sukses") {
		        	alert("Order has been added");
		        	window.location = "resto-trans.php?<?php echo trim(base64_encode('id'), '=') ?>=<?php echo $idmeja_en ?>";
		        	$('.btn-action').find('a').removeAttr('disabled');
		        	$('.btn-action').find('button').each(function(index, el) {
		        		$(this).removeAttr('disabled');
		        	});
	        	} else {
	        		alert(data);
	        	}
	        }
				})
				
			} else {
				alert("Fill the form first");
			}
		});

		$('.add-line').click(function(event) {
			event.preventDefault();
			$('.table-add-order').find('tbody').append(
				'<tr>'+
					'<td class="no"></td>'+
					'<td class="input-table-placer">'+
						'<input type="text" class="input-table input-menu">'+
						'<input type="hidden" class="idmenu">'+
					'</td>'+
					'<td style="width: 3px;"></td>'+
					'<td class="input-table-placer">'+
						'<input type="text" class="input-table input-jumlah">'+
					'</td>'+
					'<td><a href="#" class="remove-line"><i class="fa fa-times"></i></a></td>'+
				'</tr>');
			set_no();
			moveable_in_table();
		});

		$('.remove-last-line').click(function(event) {
			event.preventDefault();
			$('.table-add-order').find("tbody").find('tr:last-child').remove();
		});

		$('.btn-nota').click(function(event) {
			if ($('.act_form').val() == "new") {
				event.preventDefault();
			};
		});

		$('.btn-reset-list').click(function(event) {
			event.preventDefault();
			var r=confirm("Are you sure?");
			if (r==true) {
			  $.ajax({ 
		      type: "POST",
		      url: "/action/act_resto_menu.php",
		      data: { 
		      	idresto: $('.idresto').val(), 
		      	act: 3
		      },
		      cache: false, 
		      success: function(data){ 
		      	if (data == "sukses") {
		      		alert("List order has successfully deleted");
		      	} else {
		      		alert(data);
		      	}
		      }
		    });
			}
		});

		$('.btn-edit-list').click(function(event) {
			event.preventDefault();
			$.ajax({ 
	      type: "POST",
	      url: "/ajax/list_order.php",
	      data: { idresto: $('.idresto').val() },
	      cache: false, 
	      success: function(data){ 
	      	$('#order-placer').html(data);
	      	$('#order-list-placer').html("<tr><td colspan='5'>Nothing has been ordered yet</td></tr>");
	      }
	    });
		});

		$('.btn-delete-list').click(function(event) {
			event.preventDefault();
			var r=confirm("Are you sure?");
			if (r==true) {
			  $.ajax({ 
		      type: "POST",
		      url: "/action/act_resto_menu.php",
		      data: { 
		      	idresto: $('.idresto').val(), 
		      	act: 4
		      },
		      cache: false, 
		      success: function(data){ 
		      	if (data == "sukses") {
		      		alert("Table has been cleared");
		      		window.location = "resto.php";
		      	} else {
		      		alert(data);
		      	}
		      }
		    });
			}
		});

		$('#order-placer').on('click', '.remove-line', function(event) {
			event.preventDefault();
			$(this).closest('tr').remove();
			set_no();
		});
		
		$('#order-placer').on('keydown', '.input-menu', function(){
			$(this).typeahead({
	      source: function(typeahead, query) {
	        $.ajax({
	          url: "/action/act_resto.php",
	          dataType: "json",
	          type: "POST",
	          data: {
	          	key: query,
	          	act: 1
	          },
	          success: function(data) {
	            var return_list = [], i = data.length;
	            while (i--) {
	              return_list[i] = {id: data[i].id, value: data[i].kode + " | " + data[i].nama, nama: data[i].nama};
	            }
	            typeahead.process(return_list);
	          }
	        });
	      },
	      onselect: function(obj) {
	        this.$element.val(obj.nama);
	        this.$element.closest('td').find('.idmenu').val(obj.id);
	      }
			});
		});

		$('.plus-agent').click(function(event) {
			$("#modal-placer").fadeOut("medium",function(){
				$('body').modalmanager('loading');
		    $.ajax({ 
		      type: "POST",
		      url: "/modal/modal_agent.php",
		      cache: false, 
		      success: function(msg){ 
		      	$('body').modalmanager('loading');
		        $("#modal-placer").html(msg);
		        $("#modal-placer").fadeIn("medium");
		        $('#form-modal').modal('show');
		      } 
		    }); 
		  });
		});

		$('.plus-menu').click(function(event) {
			$("#modal-placer").fadeOut("medium",function(){
				$('body').modalmanager('loading');
		    $.ajax({ 
		      type: "POST",
		      url: "/modal/modal_menu.php",
		      cache: false, 
		      success: function(msg){ 
		      	$('body').modalmanager('loading');
		        $("#modal-placer").html(msg);
		        $("#modal-placer").fadeIn("medium");
		        $('#form-modal').modal('show');
		      } 
		    }); 
		  });
		});
	});
</script>        